package xin.yangshuai.juc01.hello;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Question8
 *
 * @author shuai
 * @date 2022/2/20
 */
public class Question8 {

    private Semaphore semaphore;

    public void setSemaphore(Semaphore semaphore) {
        this.semaphore = semaphore;
    }

    private ReentrantLock lock = new ReentrantLock();

    private void come() {

        try {
            lock.lock();

            count++;
            System.out.println(Thread.currentThread().getName() + " :: 停车 ：：" + count);
        } finally {
            lock.unlock();
        }
    }

    private void go() {
        try {
            lock.lock();

            count--;
            System.out.println(Thread.currentThread().getName() + " :: 开走 ：：" + count);
        } finally {
            lock.unlock();
        }
    }

    private int count;

    public void park() {
        try {
            semaphore.acquire();

            come();
            TimeUnit.MILLISECONDS.sleep(300);
            go();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
    }
}

class Result8 {
    public static void main(String[] args) {

        Question8 question8 = new Question8();
        question8.setSemaphore(new Semaphore(9));
        for (int i = 0; i < 20; i++) {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    question8.park();
                }
            }, String.valueOf(i)).start();
        }
    }
}
